package com.test.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.test.entity.User;
import com.test.service.UserService;
import com.test.util.jwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {

    /**
     * JWT token前缀
     */
    public static final String JWT_TOKEN = "token_jwt_";

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @param user 注册用户信息
     * @return
     */
    @RequestMapping("/registry")
    public String userRegistry(User user) {
        try {
            userService.userRegistry(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/registry.jsp";
    }

    /**
     * 用户退出登录
     *
     * @return
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 退出
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        DecodedJWT decodedJWT = jwtUtil.verifyToken(jwtToken);
        String username = decodedJWT.getClaim("username").asString();
        String key = JWT_TOKEN + username;
        //删除redis中的token
        redisTemplate.delete(key);
        //删除请求头中的token
        response.setHeader("Authorization", null);
        return "退出成功";
    }

    /**
     * 用户登录 ,shrio整合jwt进行认证
     * User  用户信息  用户名 密码
     *
     * @return
     */
    @PostMapping("/login")
    public Map login(@RequestBody User user, HttpServletResponse response) {
        HashMap<String, String> resultMap = new HashMap<>();
        //因为在config中已经配置了SecurityManager,并且也在ShiroFilter中配置了安全管理器,所以在此处可以直接使用SecurityUtiles工具类

        //用户名查询用户
        User user_db = userService.findUserByNmae(user.getUsername());
        if (user_db == null) {
            throw new RuntimeException("用户不存在");
        }

        //如果数据库密码加密了,登录用户密码加密之后进行比较.此处假设正确,然后生成token
        HashMap<String, String> userMap = new HashMap<>();
        userMap.put("userName", user.getUsername());
        String jwtToken = jwtUtil.getToken(userMap);

        //将username token放在redis中 设置过期时间
        String key = JWT_TOKEN + user.getUsername();    //token_jwt_zhangsan
        redisTemplate.opsForValue().set(key, jwtToken, 30, TimeUnit.MINUTES);

        // response携带jwt
        response.setHeader("token", jwtToken);
        response.setHeader("Access-control-Expose-Headers", "token");
        resultMap.put("code", "200");
        resultMap.put("msg", "登录成功");
        resultMap.put("token", jwtToken);
        return resultMap;
    }
    /**
     * 用户登录 ,shrio整合jwt进行认证
     * User  用户信息  用户名 密码
     * @return
     *//*
    @PostMapping("/login")
    public Map login(@RequestBody User user, HttpServletResponse response) {
        HashMap<String, String> resultMap = new HashMap<>();
        //因为在config中已经配置了SecurityManager,并且也在ShiroFilter中配置了安全管理器,所以在此处可以直接使用SecurityUtiles工具类

        //用户名查询用户
        User user_db = userService.findUserByNmae(user.getUsername());
        if (user_db == null) {
            throw new RuntimeException("用户不存在");
        }

        //如果数据库密码加密了,登录用户密码加密之后进行比较.此处假设正确,然后生成token
        HashMap<String, String> userMap = new HashMap<>();
        userMap.put("userName", user.getUsername());
        String jwtToken = jwtUtil.getToken(userMap);

        //将username token放在redis中 设置过期时间
        String key = JWT_TOKEN + user.getUsername();    //token_jwt_zhangsan
        redisTemplate.opsForValue().set(key, jwtToken, 30, TimeUnit.MINUTES);

        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new JwtToken(jwtToken));
            System.out.println("认证成功!");

            // response携带jwt
            response.setHeader("token", jwtToken);
            response.setHeader("Access-control-Expose-Headers", "token");
            resultMap.put("code", "200");
            resultMap.put("msg", "登录成功");
            resultMap.put("token", jwtToken);

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!");
            resultMap.put("code", "400");
            resultMap.put("msg", "用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误!");
            resultMap.put("code", "400");
            resultMap.put("msg", "密码错误");
        }
        return resultMap;
    }*/
}
